import 'dart:convert';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'rpc_transport.dart';

class InAppWebViewTransport implements RpcTransport {
  final InAppWebViewController controller;

  InAppWebViewTransport(this.controller);

  @override
  void send(String payload) {
    final escaped = jsonEncode(payload);
    controller.evaluateJavascript(
      source: 'window.RpcFromFlutter($escaped)',
    );
  }

  @override
  void Function(String payload)? onMessage;

  @override
  void dispose() {}

  // 提供给 JS 调用的入口
  void receiveFromJs(String payload) {
    onMessage?.call(payload);
  }
}
